import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:image_scan_crop/enum/Env.dart';
import 'package:image_scan_crop/enum/MethodTyps.dart';
import 'package:image_scan_crop/net/RequestInterceptor.dart';
import 'package:image_scan_crop/utils/ApiUtils.dart';
import 'package:image_scan_crop/utils/Config.dart';
import 'package:image_scan_crop/utils/Utils.dart';
import 'package:quiver/strings.dart';

class HttpNet {
  // 工厂模式
  factory HttpNet() => _getInstance();

  late Dio _dio;
  bool _hide = false;

  Dio get dio => _dio;

  static HttpNet get instance => _getInstance();
  static HttpNet? _instance;

  //初始化
  HttpNet._internal() {
    _initDio();
  }

  static HttpNet _getInstance() {
    if (_instance == null) {
      _instance = new HttpNet._internal();
    }
    return _instance!;
  }

  _initDio() {
    _dio = new Dio();
    _dio.options.receiveTimeout = 15 * 1000;
    _dio.options.baseUrl = Config.apiHost;
    _dio.options.responseType = ResponseType.json;
    _dio.interceptors
        .add(LogInterceptor(responseBody: true, requestBody: true));
    _dio.interceptors.add(RequestInterceptor(hide: _hide));
  }

  MethodTypes? _tempTypes;
  String? _tempPath;
  Map<String, dynamic>? _tempParams;
  dynamic _tempData;
  bool? _tempHide;
  Map<String, dynamic>? _tempHeaders;
  String? _tempContentType;

  Future<dynamic> request<T>(MethodTypes methodTypes, String path,
      {Map<String, dynamic>? params,
      dynamic data,
      bool? hide,
      Map<String, dynamic>? headers,
      String? contentType,
      Function? relogin}) async {
    this._tempTypes = methodTypes;
    this._tempPath = path;
    this._tempParams = params;
    this._tempData = data;
    this._tempHide = hide;
    this._tempHeaders = headers;
    this._tempContentType = contentType;
    CancelToken token = new CancelToken();
    if (headers == null) headers = {};
    if (path != "${ApiUtils.APP}${ApiUtils.retrievePassword}") {
      if (path == ApiUtils.getAuth) {
        headers["Authorization"] =
            "Basic ${Base64Encoder().convert(Utf8Encoder().convert("latm:latm"))}";
      } else {}
    }
    if (Config.env == Env.DEV) headers["z-l-t-version"] = "xx";
    var options = new Options(headers: headers, contentType: contentType);
    try {
      Response<String> sValue;
      if (methodTypes == MethodTypes.GET) {
        sValue = await _dio.get(path,
            queryParameters: params ?? null,
            options: options,
            cancelToken: token);
      } else if (methodTypes == MethodTypes.POST) {
        sValue = await _dio.post(path,
            options: options,
            data: data ?? null,
            queryParameters: params,
            cancelToken: token);
      }
      // if (sValue != null && isNotEmpty(sValue.data) && sValue.data != "null" && sValue.statusCode == 200) {
      //   token.cancel();
      //   BaseResponse response = BaseResponse.fromJsonBase(jsonDecode(sValue.data));
      //   if (response.code == 0) {
      //     return response.data ?? response;
      //   } else if (response.code == 500) {
      //     Utils.showToast("服务端数据出错");
      //     return;
      //   } else {
      //     Utils.showToast(response.message ?? "数据返回错误");
      //     return;
      //   }
      // } else if (sValue?.statusCode == 401) {
      //   _loginTimeOut();
      // } else {
      //   throw ("服务器返回数据错误");
      // }
    } catch (error) {
      EasyLoading.dismiss();
      if (error is DioError) {
        DioError err = error;
        if (err.response != null) {
          // if (err.response?.statusCode == 401) {
          //   _loginTimeOut();
          // } else {
          //   try {
          //     BaseResponse response = BaseResponse.fromJsonBase(jsonDecode(err.response.toString()));
          //     Utils.showToast("${response.message} code: ${err.response.statusCode}");
          //   } catch (e) {
          //     Utils.showToast("服务端数据出错");
          //   }
          // }
        } else {
          // Utils.showToast(err.message);
          Utils.showToast("网络错误，请检查网络");
        }
      } else {
        Utils.showToast(error.toString());
        // throw ("请求发生异常");
      }
    }
  }

  // Future<void> _reflashToken() async {
  //   String refresh = await Utils.getInfo("refresh");
  //   var head = {"Authorization": "Basic ${Base64Encoder().convert(Utf8Encoder().convert("latm:latm"))}"};
  //   Map<String, dynamic> params = Map<String, dynamic>();
  //   params["grant_type"] = "refresh_token";
  //   params["openId"] = refresh;
  //   Response response = await _dio.post("${ApiUtils.getAuth}", options: Options(headers: head), data: FormData.fromMap(params));
  //   if (response.statusCode == 200) {
  //     BaseResponse baseModel = BaseResponse.fromJsonBase(jsonDecode(response.data));
  //     AuthModel authModel = AuthModel.fromJson(baseModel.data);
  //     ApiUtils.loginToken = authModel;
  //     Utils.saveInfo("token", authModel.access_token);
  //     Utils.saveInfo("refresh", authModel.refresh_token);
  //   }
  // }

  // _loginTimeOut() async {
  //   // Utils.showToast("会话超时，请重新登录");
  //   // waitRelogin(DRouters.navigatorKey.currentContext);
  //   await Utils.removeInfo("token");
  //   _reflashToken().then((value) {
  //     request(_tempTypes, _tempPath, params: _tempParams, data: _tempData, hide: _tempHide, headers: _tempHeaders, contentType: _tempContentType);
  //   }).catchError((err) async {
  //     ApiUtils.loginToken = null;
  //     await Utils.removeInfo("token");
  //     await Utils.removeInfo("refresh");
  //     waitRelogin(DRouters.navigatorKey.currentContext);
  //     Utils.showToast("登录会话超时，请重新登录");
  //   });
  // }

  Dio initOptionDio() {
    Dio _dio = new Dio();
    _dio.options.receiveTimeout = 15 * 1000;
    _dio.options.responseType = ResponseType.json;
    _dio.interceptors
        .add(LogInterceptor(responseBody: true, requestBody: true));
    _dio.interceptors.add(RequestInterceptor(hide: _hide));
    return _dio;
  }
}
